<template>
  <div>
    <vxe-modal v-model="visible" title="多属性选择" width="600" show-zoom resize show-footer>
      <template #default>
        <el-scrollbar style="height: 60vh">
          <el-form :model="form" ref="formRef" label-width="120px" label-position="left">
            <template v-for="(item, index) in list" :key="item.label">
              <el-form-item>
                <template v-slot:label>
                  <el-checkbox v-model="item.checked" label="" @change="checked(item, index)" />
                  <span class="ml-3">
                    {{ item.label }}
                  </span>
                </template>
                <el-select class="w-full" v-model="item.value" multiple clearable collapse-tags collapse-tags-tooltip
                  filterable allow-create default-first-option :reserve-keyword="false" placeholder="请选择">
                  <el-option v-for="o in item.options" :key="o" :label="o" :value="o" />
                </el-select>
              </el-form-item>
            </template>
          </el-form>
        </el-scrollbar>
      </template>
      <template #footer>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="save(formRef)">确 认</el-button>
      </template>
    </vxe-modal>
  </div>
</template>
<script setup name="Attribute">
import { reactive, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
const emits = defineEmits(['selectAttribute'])
const data = reactive({
  visible: false,
  loading: false,
  list: [],
  value: [],
  form: {},
  selectAttribute: []
})
const { selectAttribute, form, list, visible, formRef } = toRefs(data)

const open = (data) => {
  visible.value = true
  list.value = data
}
// 选中
const checked = (item, index) => {
  if (item.checked && selectAttribute.value.length > 1) {
    list.value[index].checked = false
    return ElMessage.error('最多只能选择2个属性')
  }
  selectAttribute.value = list.value.filter((item) => item.checked)
}
// 选中多属性
const save = () => {
  let arr = []
  selectAttribute.value.forEach((item) => {
    arr.push({
      label: item.label,
      value: item.value,
      options: item.options
    })
  })
  emits('selectAttribute', arr)
  selectAttribute.value = []
  close()
}
const close = () => {
  visible.value = false
}
defineExpose({ open })
</script>
